home *** CD-ROM | disk | FTP | other *** search
- Path: news.iag.net!news
- From: jatmon@iag.net (John R Buchan)
- Newsgroups: comp.lang.c
- Subject: Re: Trouble with file return code.
- Date: 11 Jan 1996 17:27:02 GMT
- Organization: Internet Access Group, Orlando, Florida
- Message-ID: <4d3h96$9fl@news.iag.net>
- References: <tcpnntpd.16.1.10.20.22.42.2781597121.333610@the-fix.sos.on.ca>
- NNTP-Posting-Host: pm3-orl4.iag.net
- X-Newsreader: WinVN 0.99.7
-
- In article <tcpnntpd.16.1.10.20.22.42.2781597121.333610@the-fix.sos.on.ca>,
- xenon@the-fix.sos.on.ca says...
- >
- > Im having some trouble getting fread to return NULL when it can't
- >find a specific file...
- >
- > else if((ptr=fread(filename1,"rb"))!=NULL)
- > {
- > //do this }
- > else {
- > // do that
- > // this never executes, even if NULL is returned.
- >No matter the file, Null is never returned. Although, when the variable
- >ptr is outputed, the value shown is "0".
-
- ?? No ansi compiler will even compile this code. So, how could you possible
- determine that NULL is not being returned? The prototype for fread is:
-
- size_t fread( void *ptr, size_t size, size_t nobj, FILE *stream);
-
- fread returns the number of objects read, not a pointer. Try this:
-
- #include <stdio.h>
- #include <stdlib.h>
-
- int main(void)
- {
- FILE *ptr;
- char filename[] = "tmp.dat";
- char buf[20];
-
- if ((ptr = fopen(filename, "rb")) == NULL)
- {
- fprintf(stderr, "Cannot open file.\n");
- exit( EXIT_FAILURE);
- }
-
- /* Of course, you'll want to do better i/o testing, but basically */
- while( fread(buf, sizeof(buf), 1, ptr) == 1)
- {
- /* play with the data */
- }
-
- fclose(ptr);
- return 0;
- }
-
- BTW, you should try to post a minimum complete compilable example that
- produces your error. You should also d/l and read through the c.l.c faq
- (Frequently Asked Question) list. It contains answers for many of the
- common gotcha's in c programming. It is available for anonymous ftp from
- rtfm.mit.edu /pub/usenet/comp.lang.c.
-
- --
- John R Buchan -:|:- Looking for that elusive FAQ? ftp to:
- jatmon@mail.iag.net -:|:- rtfm.mit.edu /pub/usenet-by-group/....
-
-